<template>
  <el-container>
    <el-form
      :model="form"
      label-width="120px"
      size="small"
      style="width: 100%"
    >
      <el-container v-loading="formLoading">
        <el-header height="50%">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item v-if="baseInfo.type === 'building'" label="楼栋名称">
                <el-input v-model="form.building_name" disabled />
              </el-form-item>
              <el-form-item v-else label="单元名称">
                <el-input v-model="form.unit_name" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单元数量">
                <el-input-number
                  v-model="form.unitNum"
                  controls-position="right"
                  :min="0"
                  size="small"
                  :disabled="baseInfo.type === 'unit' || baseInfo.childType === 'room'"
                  @change="unitNumChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-button
                  type="primary"
                  :disabled="disabledAdd || baseInfo.childType === 'unit'"
                  @click="addDefinition"
                >新增房屋定义</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-header>
        <el-main>
          <el-table
            ref="formTable"
            :data="form.unitList"
            tooltip-effect="dark"
            height="500"
            style="width: 100%"
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-form ref="form" label-position="left" :model="scope.row" :rules="rules" inline class="demo-table-expand">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="建筑性质" prop="fbuildingpropertyid">
                        <el-select v-model="scope.row.fbuildingpropertyid" filterable placeholder="请选择" style="width: 100%">
                          <el-option
                            v-for="item in dictData.buildingPropertyEnum"
                            :key="item.fid"
                            :label="item.fnameL2"
                            :value="item.fid"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="产品类型" prop="fproducttypeid">
                        <el-select v-model="scope.row.fproducttypeid" filterable placeholder="请选择" style="width: 100%">
                          <el-option
                            v-for="item in dictData.producttypeEnum"
                            :key="item.fid"
                            :label="item.fnameL2"
                            :value="item.fid"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="销售类型" prop="cfsaletypeid">
                        <el-select v-model="scope.row.cfsaletypeid" filterable placeholder="请选择" style="width: 100%">
                          <el-option
                            v-for="item in dictData.saleTypeEnum"
                            :key="item.fid"
                            :label="item.fnameL2"
                            :value="item.fid"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="数字转字母">
                        <el-checkbox v-model="scope.row.isLetter" style="margin-left: 20px" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column
              label="单元名称"
              min-width="120"
              align="center"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.unitName" :disabled="!disabledAdd" size="small" />
              </template>
            </el-table-column>
            <el-table-column
              label="单元号"
              min-width="150"
              align="center"
            >
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.unitNo" :disabled="!disabledAdd" controls-position="right" size="small" />
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="开始楼层"
              min-width="150"
              align="center"
            >
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.startFloor" controls-position="right" size="small" />
              </template>
            </el-table-column>
            <el-table-column
              label="结束楼层"
              min-width="150"
              align="center"
            >
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.endFloor" controls-position="right" size="small" />
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="开始序号"
              min-width="150"
              align="center"
            >
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.startRoomSort" controls-position="right" :min="1" size="small" />
              </template>
            </el-table-column>
            <el-table-column
              label="结束序号"
              min-width="150"
              align="center"
            >
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.endRoomSort" controls-position="right" :min="1" size="small" />
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="80"
              align="center"
            >
              <template slot-scope="scope">
                <el-button type="danger" size="small" @click="removeDefinition(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
        <el-footer :style="{'text-align': menuAlign}">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button type="primary" @click="resetForm">重置</el-button>
        </el-footer>
      </el-container>
    </el-form>
  </el-container>
</template>

<script>
import { addBatchRoom } from '@/api/baseManage/houseManage'
export default {
  name: 'BatchAddRoom',
  components: {
  },
  props: {
    dictData: { type: Object, default() {
      return {
        buildingPropertyEnum: [],
        producttypeEnum: [],
        saleTypeEnum: []
      }
    } },
    baseInfo: { type: Object, default() { return {} } },
    menuAlign: { type: String, default: 'center' }
  },
  data() {
    return {
      disabledAdd: false,
      /* 表单数据 */
      form: {
        building_name: '',
        unitNum: 0,
        unitList: []
      },
      dialogVisible: false,
      /* 表单验证规则 */
      rules: {
        fbuildingpropertyid: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        fproducttypeid: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        cfsaletypeid: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      },
      formLoading: false
    }
  },
  create() {
  },
  watch: {
    baseInfo: {
      immediate: true,
      handler(val) {
        if (this.baseInfo.type === 'building') {
          this.form.fbuildingid = this.baseInfo.fid
          this.form.building_name = this.baseInfo.fnameL2
        } else {
          this.form.fbuildingid = this.baseInfo.fbuildingid
          this.form.fbuildunitid = this.baseInfo.fid
          this.form.unit_name = this.baseInfo.fnameL2
        }
      }
    }
  },
  methods: {
    unitNumChange(currentValue, oldValue) {
      if (currentValue > 0) {
        this.disabledAdd = true
      } else {
        this.disabledAdd = false
      }
      if (currentValue > this.form.unitList.length) {
        const count = currentValue - this.form.unitList.length
        for (let i = 0; i < count; i++) {
          this.addDefinition()
        }
      } else if (currentValue < this.form.unitList.length) {
        this.form.unitList = this.form.unitList.slice(0, currentValue)
      }
    },
    /**
     * 提交表单
     */
    submitForm() {
      const definitions = this.form.unitList
      if (definitions.length === 0) {
        this.$message.warning(`房屋定义不能为空`)
        return
      }
      if (!this.disabledAdd) {
        for (let i = 0; i < definitions.length; i++) { // 楼层序号不能重复
          for (let j = 0; i < definitions.length; i++) {
            if (i !== j) {
              if (definitions[i].startFloor === definitions[j].startFloor &&
                definitions[i].endFloor === definitions[j].endFloor &&
                definitions[i].startRoomSort === definitions[j].startRoomSort &&
                definitions[i].endRoomSort === definitions[j].endRoomSort) {
                this.$message.warning(`房屋定义第${j + 1}行 与 第${i + 1}行重复`)
                return
              }
              if (intersection(definitions[i], definitions[j])) {
                this.$message.warning({
                  message: `房屋定义第${j + 1}行 与 第${i + 1}行 相同楼层序号不能重复`,
                  duration: 5000
                })
                return
              }
            }
          }
        }
      }

      for (let i = 0; i < definitions.length; i++) {
        const definition = definitions[i]
        if (!definition.unitName && this.disabledAdd) {
          this.$message.warning(`房屋定义第${i + 1}行，单元名称不能为空`)
          return
        }
        if (definitions.filter(v => v.unitName && v.unitName === definition.unitName).length > 1) {
          this.$message.warning(`房屋定义第${i + 1}行，单元名称已存在`)
          return
        }
        if (!definition.unitNo && this.disabledAdd) {
          this.$message.warning(`房屋定义第${i + 1}行，单元号不能为空`)
          return
        }
        if (definitions.filter(v => v.unitNo && v.unitNo === definition.unitNo).length > 1) {
          this.$message.warning(`房屋定义第${i + 1}行，单元号已存在`)
          return
        }
        if (!definition.startFloor) {
          this.$message.warning(`房屋定义第${i + 1}行，开始楼层不能为空`)
          return
        }
        if (definition.startFloor === 0) {
          this.$message.warning(`房屋定义第${i + 1}行，开始楼层不能为0`)
          return
        }
        if (!definition.endFloor) {
          this.$message.warning(`房屋定义第${i + 1}行，结束楼层不能为空`)
          return
        }
        if (definition.endFloor === 0) {
          this.$message.warning(`房屋定义第${i + 1}行，结束楼层不能为0`)
          return
        }
        if (definition.endFloor < definition.startFloor) {
          this.$message.warning(`房屋定义第${i + 1}行，结束楼层不能小于开始楼层`)
          return
        }
        if (!definition.startRoomSort) {
          this.$message.warning(`房屋定义第${i + 1}行，开始序号不能为空`)
          return
        }
        if (!definition.endRoomSort) {
          this.$message.warning(`房屋定义第${i + 1}行，结束序号不能为空`)
          return
        }
        if (definition.endRoomSort < definition.startRoomSort) {
          this.$message.warning(`房屋定义第${i + 1}行，结束序号不能小于开始序号`)
          return
        }
        if (!definition.fbuildingpropertyid) {
          this.$message.warning(`房屋定义第${i + 1}行，请选择建筑性质`)
          return
        } if (!definition.fproducttypeid) {
          this.$message.warning(`房屋定义第${i + 1}行，请选择产品类型`)
          return
        } if (!definition.cfsaletypeid) {
          this.$message.warning(`房屋定义第${i + 1}行，请选择销售类型`)
          return
        }
      }
      this.formLoading = true
      addBatchRoom(this.form).then(rv => {
        if (rv.code === 200) {
          this.$emit('onSuccess')
          this.$message.success('生成成功')
          this.$eventBus.$emit('unitUpdate', this.form.fbuildingid)
        } else {
          this.$message.error(rv.msg ? rv.msg : '生成失败')
        }
      }).finally(() => {
        this.formLoading = false
      })
      function intersection(row1, row2) { // 判断两行是否有相同楼层序号重复
        const row1FloorArr = []
        for (let i = row1.startFloor; i <= row1.endFloor; i++) {
          row1FloorArr.push(i)
        }
        const row2FloorArr = []
        for (let i = row2.startFloor; i <= row2.endFloor; i++) {
          row2FloorArr.push(i)
        }
        let isFloorAlike = false // 两行楼层是否有相同
        row1FloorArr.forEach(item => {
          if (row2FloorArr.includes(item)) {
            isFloorAlike = true
          }
        })
        if (isFloorAlike) {
          const row1RoomArr = []
          for (let i = row1.startRoomSort; i <= row1.endRoomSort; i++) {
            row1RoomArr.push(i)
          }
          const row2RoomArr = []
          for (let i = row2.startRoomSort; i <= row2.endRoomSort; i++) {
            row2RoomArr.push(i)
          }
          let isRoomAlike = false // 两行楼层是否有相同
          row1RoomArr.forEach(item => {
            if (row2RoomArr.includes(item)) {
              isRoomAlike = true
            }
          })
          return isRoomAlike
        }
        return false
      }
    },
    /**
     * 重新表单
     */
    resetForm() {
      this.form.unitNum = 0
      this.form.unitList = []
    },
    addDefinition() {
      const index = this.form.unitList.length
      this.form.unitList.push({
        $index: index,
        fbuildingpropertyid: '',
        fproducttypeid: '',
        cfsaletypeid: '',
        isLetter: false
      })
      this.$nextTick(() => {
        this.$refs.formTable.toggleRowExpansion(this.form.unitList[index])
      })
    },
    removeDefinition(row) {
      const index = row.$index
      this.form.unitList.splice(index, 1)
      this.form.unitList = this.form.unitList.map(v => {
        if (v.$index > index) {
          v.$index -= 1
        }
        return v
      })
    }
  }
}
</script>
<style>
  .img-placeholder {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    color: #909399;
  }
  .expanded td:nth-child(1) {
    border-bottom: none;
  }
</style>
